package com.thiswhyme.sentinel.server1.instance2.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.thiswhyme.common.response.ResponseVo;
import com.thiswhyme.sentinel.server1.instance2.controller.dto.UserDto;

/**
 * 注解+代码方式demo
 * Created by thiswhyme on 2020/8/16.
 */
@RestController
@RequestMapping("/code-demo/")
public class CodeDemoController {

    /**
     * 限流&熔断 -有blockHandler
     * @param userId
     * @return
     */
    @SentinelResource(value = "user-name", //资源名
            blockHandler = "queryUserNameBlockHandle"
    )
    @GetMapping("user-name")
    public ResponseVo<String> queryUserName(@RequestParam Integer userId) {
        return ResponseVo.success("user-name-" + userId);
    }

    public ResponseVo<String> queryUserNameBlockHandle(Integer userId, BlockException e) {
        e.printStackTrace();
        return ResponseVo.failure("403", String.format("queryUserName限流处理, userId：%s, errMsg: %s", userId, e.getMessage()));
    }

    /**
     * 限流&熔断 -指定了资源名
     * @return
     */
    @SentinelResource(value = "user-info")
    @GetMapping("user-info")
    public ResponseVo<UserDto> queryUserInfo() {
        return ResponseVo.success(new UserDto().setUserId(666).setName("user-info"));
    }

    /**
     * 限流 -未指定资源名
     * @return
     */
    @GetMapping("user-info2")
    public ResponseVo<UserDto> queryUserInfo2() {
        return ResponseVo.success(new UserDto().setUserId(666).setName("user-info2"));
    }
}
